package com.itany.book.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itany.constant.StatusConst;
import com.itany.exception.ManagerServiceException;
import com.itany.mapper.BookMapper;
import com.itany.mapper.BookSupplierMapper;
import com.itany.mapper.ExamineMapper;
import com.itany.mapper.SupplierMapper;
import com.itany.pojo.*;
import com.itany.service.ExamineService;
import com.itany.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ResourceUtils;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Service
@Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
public class ExamineServiceImpl implements ExamineService {
    @Autowired
    BookMapper bookMapper;
    @Autowired
    ExamineMapper examineMapper;

    @Autowired
    SupplierMapper supplierMapper;

    @Autowired
    BookSupplierMapper bookSupplierMapper;

    @Override
    public void addExamine(Integer supplierid, BookWithBLOBs book, CommonsMultipartFile file) throws ManagerServiceException {
        //待审核书籍数量
        Integer number = book.getNumber();
        //校验 isbn
        if (StringUtils.isEmpty(book.getIsbn())) {
            throw new ManagerServiceException("ISBN错误");
        }

        // 数据库根据isbn查找
        BookExample bookExample = new BookExample();
        bookExample.or()
                .andIsbnEqualTo(book.getIsbn());
        List<Book> books = bookMapper.selectByExample(bookExample);
        // 没有就创建
        if (books.isEmpty()) {
            book.setFlag(StatusConst.DISABLE);
            book.setNumber(0);
            book.setCreatetime(new Date());
            bookMapper.insertSelective(book);
        } else {
            book.setId(books.get(0).getId());
        }
        try {
            // 已有还要更新图片
            String relPath = StatusConst.IMAGE_ROOT_DIRECTORY + new SimpleDateFormat("yyyyMMdd").format(new Date());
            String absPath = ResourceUtils.getURL("classpath:").getPath() + "/resources/" + relPath;
            String fileName = null;
            if (file != null && !file.isEmpty()) {
                fileName = StringUtils.rename(file.getOriginalFilename());
                book.setImgurl(relPath + "/" + fileName);
                bookMapper.updateByPrimaryKeySelective(book);
            }
            Examine examine = new Examine();
            examine.setFlag(StatusConst.DISABLE);
            examine.setBookid(book.getId());
            examine.setNumber(number);
            examine.setSupplierid(supplierid);

            Supplier supplier = supplierMapper.selectByPrimaryKey(supplierid);
            String supplierName = null;
            if (supplier != null) {
                supplierName = supplier.getName();
            }

            examine.setTitle(supplierName + " :" + book.getBookname());
            examineMapper.insertSelective(examine);

            if (file != null && !file.isEmpty()) {
                new File(absPath).mkdirs();
                file.transferTo(new File(absPath, fileName));
            }
        } catch (IOException e) {
            throw new ManagerServiceException("文件上传出错");
        }
    }

    @Override
    public PageInfo<Examine> findBooksByExample(Integer page, Integer rows, String bookName, String isbn, Integer supplierId) throws ManagerServiceException {
        //数据校验
//        if (StringUtils.isEmpty(bookName) || StringUtils.isEmpty(isbn)) {
//            throw new ManagerServiceException("数据为空");
//        }
        PageHelper.startPage(page, rows);
        List<Examine> examines = examineMapper.selectAllWithBookSupplier(bookName, isbn, supplierId);
        PageInfo<Examine> info = new PageInfo<>(examines);
        return info;
    }

    @Override
    public Examine findById(Integer id) {

        Examine examine = examineMapper.selectByPrimaryKey(id);

        if (examine != null) {
            Integer bookid = examine.getBookid();
            BookWithBLOBs book = bookMapper.selectByPrimaryKey(bookid);
            examine.setBook(book);
        }

        return examine;
    }

    @Override
    public Examine update(Integer id, Integer flag, String info) throws ManagerServiceException {
        Examine examine = examineMapper.selectByPrimaryKey(id);
        if (examine == null) {
            throw new ManagerServiceException("不存在该审核");
        }
        if (examine.getFlag() != StatusConst.DISABLE) {
            throw new ManagerServiceException("审核已通过,不能驳回");
        }
        examine.setInfo(info);
        examine.setFlag(flag);

        examineMapper.updateByPrimaryKeySelective(examine);

        // 未通过
        if (flag != StatusConst.ENABLE) {
            return examine;
        }

        BookSupplierExample example = new BookSupplierExample();
        example.or().andBookidEqualTo(examine.getBookid())
                .andSupplieridEqualTo(examine.getSupplierid());
        List<BookSupplier> bookSuppliers = bookSupplierMapper.selectByExample(example);
        // 没有就创建
        if (bookSuppliers.isEmpty()) {
            BookSupplier bookSupplier = new BookSupplier();
            bookSupplier.setBookid(examine.getBookid());
            bookSupplier.setSupplierid(examine.getSupplierid());
            bookSupplier.setNumber(0);
            bookSupplier.setSellnum(0);
            bookSupplierMapper.insert(bookSupplier);
        }
        bookSuppliers = bookSupplierMapper.selectByExample(example);
        BookSupplier bookSupplier = bookSuppliers.get(0);

        bookSupplier.setNumber(examine.getNumber() + bookSupplier.getNumber());
        bookSupplierMapper.updateByPrimaryKeySelective(bookSupplier);
        return examine;
    }
}
